package com.tjp.eight.ui.fragment.commentdetails;

import android.content.DialogInterface;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tjp.eight.R;
import com.tjp.eight.ResultModel;
import com.tjp.eight.ui.fragment.BaseFragment;
import com.tjp.eight.ui.fragment.comment.CommentZanModel;
import com.tjp.eight.ui.fragment.comment.SendCommentPostModel;
import com.tjp.eight.ui.fragment.comment.SendCommentResultModel;
import com.tjp.eight.ui.fragment.comment.ZanCommentResultModel;
import com.tjp.eight.utils.ActivityUtils;
import com.tjp.eight.utils.AppUtils;
import com.tjp.eight.utils.IsSuccessUtils;
import com.tjp.eight.utils.SharePreferencesUtils;
import com.tjp.eight.utils.StringUtils;
import com.tjp.eight.utils.ToatUtils;
import com.tjp.eight.views.DialogSendingComment;
import com.tjp.eight.views.LogoutDailog;
import com.tjp.eight.views.SendCommentBDialog;
import com.tjp.eight.views.emoj.EmojiUtil;
import com.tjp.eight.views.rcview.EndlessRecyclerOnScrollListener;
import com.tjp.eight.views.rcview.HeaderViewRecyclerAdapter;

import java.io.IOException;

/**
 * Created by Administrator on 2017/2/24.
 */
public class CommentDetailsFragment extends BaseFragment<CommentDetailsPresenter> implements CommentDetailsView, View.OnLayoutChangeListener {
    private String coid = "";
    public String cid = "";
    private int page = 1;
    private RecyclerView recyclerView;
    private CommentDetailsAdapter commentDetailsAdapter;
    private HeaderViewRecyclerAdapter headerViewRecyclerAdapter;
    private TextView tv_send_comment_;
    private View footView;
    private EditText et_comment_detail;
    private RelativeLayout rl_comment_rep;
    private LinearLayoutManager linearLayoutManager;
    private SendCommentBDialog sendCommentBDialog;
    private boolean isSending = false;
    private int commentPos = 0;
    private String currentCoid = "";
    private int zanPos = 0;
    private LogoutDailog dialogLogin;
    private DialogSendingComment sendingLoad;
    private int screenHeight = 0;
    private int keyBordHeight = 0;
    private int screenWidth = 0;

    @Override
    protected CommentDetailsPresenter createPresenter() {
        return new CommentDetailsPresenter(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = super.onCreateView(inflater, container, savedInstanceState);
        if (contentView == null) {
            contentView = inflater.inflate(R.layout.fragment_comment_details_layout, container, false);
        }
        coid = getActivity().getIntent().getStringExtra("coid");
        cid = getActivity().getIntent().getStringExtra("cid");
        initViews();
        contentView.addOnLayoutChangeListener(this);
        initHeight();
        return contentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        presenter.loadData(getJson());
    }


    @Override
    public void loadData(CommentDetailResultModel model) {
        if (model != null) {
            if (IsSuccessUtils.isSuccess(model.result)) {
                commentDetailsAdapter.setModel(model);
                page = page + 1;
                if (model.data == null || model.data.comment_list == null || model.data.comment_list.isEmpty() || model.data.comment_list.size() <= 4) {
                    headerViewRecyclerAdapter.removeFootByIndex(0);
                } else {
                    if (headerViewRecyclerAdapter.getFooterCount() == 0) {
                        headerViewRecyclerAdapter.addFooterView(footView);
                    }
                }
            } else {
                page = page - 1;
                if (page < 1) {
                    page = 1;
                }
            }
            showDialog("我来说两句~~");
        }
    }

    @Override
    public void loadMoreData(CommentDetailResultModel model) {
        if (model == null) return;
        if (IsSuccessUtils.isSuccess(model.result)) {
            commentDetailsAdapter.addItemModel(model);
            page = page + 1;
            if (model.data == null || model.data.comment_list == null || model.data.comment_list.isEmpty() || model.data.comment_list.size() <= 4) {
                headerViewRecyclerAdapter.removeFootByIndex(0);
            } else {
                if (headerViewRecyclerAdapter.getFooterCount() == 0) {
                    headerViewRecyclerAdapter.addFooterView(footView);
                }
            }
        } else {
            page = page - 1;
            if (page < 1) {
                page = 1;
            }
        }
    }

    @Override
    public void loadFail(String msg) {
        ToatUtils.toastCommentFail(getContext(), msg);
    }

    @Override
    public void sendComment(SendCommentResultModel model) {
        hideLoading();
        if (model == null) return;
        if (model.money_msg != null) {
            ToatUtils.toastCommentSuccess(getContext(), "完成" + model.money_msg.info + "\n获取" + model.money_msg.money + "金币");
            AppUtils.refreshMe();
        }
        if (IsSuccessUtils.isSuccess(model.result)) {
            et_comment_detail.setText("");
            if (sendCommentBDialog == null) {
                sendCommentBDialog = new SendCommentBDialog(getActivity());
            }
            sendCommentBDialog.setText("");
            ToatUtils.toastCommentSuccess(getActivity());
            commentDetailsAdapter.addComment(model.data);
        } else {
            ToatUtils.toastCommentFail(getActivity(), model.msg);
        }
        isSending = false;
        commentPos = 0;
        currentCoid = "";
    }

    @Override
    public void zanSuccess(ZanCommentResultModel model) {
        hideLoading();
        if (model == null) return;
        if (model.money_msg != null) {
            ToatUtils.toastCommentSuccess(getContext(), "完成" + model.money_msg.info + "\n获取" + model.money_msg.money + "金币");
            AppUtils.refreshMe();
        }
        if (IsSuccessUtils.isSuccess(model.result)) {
            commentDetailsAdapter.zanPosition(zanPos, model.do_type, model.praise);
        } else {
            ToatUtils.toastCommentFail(getContext(), model.msg);
        }
    }

    public String getZanJson(String coid) {
        CommentZanModel model = new CommentZanModel();
        model.coid = coid;
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        String json = new Gson().toJson(model);
        return json;
    }

    private void initHeight() {
        Display display = getActivity().getWindowManager().getDefaultDisplay();
        Point point = new Point();
        display.getSize(point);
        screenHeight = point.y;
        screenWidth = point.x;

        keyBordHeight = screenHeight / 3;
    }

    void initViews() {
        recyclerView = (RecyclerView) contentView.findViewById(R.id.rv_comment_details);
        et_comment_detail = (EditText) contentView.findViewById(R.id.et_comment_detail);
        et_comment_detail.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                showDialog("我来说两句~~");
                return false;
            }
        });
        linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        rl_comment_rep = (RelativeLayout) contentView.findViewById(R.id.rl_comment_rep);
        recyclerView.setLayoutManager(linearLayoutManager);
        commentDetailsAdapter = new CommentDetailsAdapter(getActivity());
        commentDetailsAdapter.setCoid(coid);
        commentDetailsAdapter.setCommentDetailsZanClick(new CommentDetailsAdapter.ItemCommentDetailsZanClick() {
            @Override
            public void ItemDetailZanClick(int position, String coid) {
                if (!SharePreferencesUtils.isLogin()) {
                    showIsLogin();
                    return;
                }
                showLoading();
                zanPos = position;
                presenter.zanCommentDetails(getZanJson(coid));
            }
        });
        commentDetailsAdapter.setItemClcik(new CommentDetailsAdapter.ItemClcik() {
            @Override
            public void repeat(String coid, String name) {
                currentCoid = coid;
                showDialog("回复：" + name);
            }
        });
        footView = LayoutInflater.from(getContext()).inflate(R.layout.swipe_refresh_footer, recyclerView, false);
        headerViewRecyclerAdapter = new HeaderViewRecyclerAdapter(commentDetailsAdapter);
        headerViewRecyclerAdapter.addFooterView(footView);
        recyclerView.setAdapter(headerViewRecyclerAdapter);
        recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                page = currentPage;
                presenter.loadMoreData(getJson());
            }
        });

        tv_send_comment_ = (TextView) contentView.findViewById(R.id.tv_send_comment_);
        tv_send_comment_.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = et_comment_detail.getText().toString();
                if (StringUtils.isNullOrEmpty(msg)) return;
                showLoading();
                if (StringUtils.isNullOrEmpty(currentCoid))
                    presenter.sendComment(getSendCommentJson(msg, coid));
                else
                    presenter.sendComment(getSendCommentJson(msg, currentCoid));

                et_comment_detail.setText("");

            }
        });
    }

    public void hideSendComment() {
        if (sendCommentBDialog != null) {
            sendCommentBDialog.dismiss();
        }
    }

    private void showDialog(String hint) {
        if (sendCommentBDialog == null) {
            sendCommentBDialog = new SendCommentBDialog(getActivity());
        }
        et_comment_detail.clearFocus();
        et_comment_detail.setEnabled(false);
        if (!SharePreferencesUtils.isLogin()) {
            showIsLogin();
            return;
        }
        rl_comment_rep.setVisibility(View.GONE);
        sendCommentBDialog.show();
        sendCommentBDialog.setHinText(hint + "");
        sendCommentBDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (!isSending) {
                    commentPos = 0;
                    currentCoid = "";
                }
                try {
                    String msg = sendCommentBDialog.getText();
                    et_comment_detail.setText("");
                    new EmojiUtil().handlerEmojiText(et_comment_detail, msg, getActivity());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                rl_comment_rep.setVisibility(View.VISIBLE);
                et_comment_detail.setEnabled(true);
            }
        });
        sendCommentBDialog.setSendComment(new SendCommentBDialog.SendComment() {
            @Override
            public void sendComment(String msg) {
                isSending = true;
                sendCommentBDialog.dismiss();
                if (StringUtils.isNullOrEmpty(msg)) return;
                showLoading();
                if (StringUtils.isNullOrEmpty(currentCoid))
                    presenter.sendComment(getSendCommentJson(msg, coid));
                else
                    presenter.sendComment(getSendCommentJson(msg, currentCoid));
                et_comment_detail.setText("");
            }
        });
    }

    private String getJson() {
        CommentDetailPostModel postModel = new CommentDetailPostModel();
        postModel.coid = coid;
        postModel.page = page;
        postModel.uid = SharePreferencesUtils.getUid();
        postModel.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(postModel);
    }

    private String getSendCommentJson(String msg, String coid) {
        SendCommentPostModel postModel = new SendCommentPostModel();
        postModel.coid = coid;
        postModel.detail = msg;
        postModel.uid = SharePreferencesUtils.getUid();
        postModel.loginkey = SharePreferencesUtils.getLoginKey();

        String json = new Gson().toJson(postModel);
        return json;
    }

    void showIsLogin() {
        if (dialogLogin == null) {
            dialogLogin = new LogoutDailog(getActivity());
        }
        dialogLogin.setTextTitle("亲！你还没登录呢");
        dialogLogin.setLogoutInterface(new LogoutDailog.LogoutInterface() {
            @Override
            public void logout() {
                ActivityUtils.startLoginForResult(getActivity());
                dialogLogin.dismiss();
            }
        });
        dialogLogin.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                et_comment_detail.setEnabled(true);
            }
        });
        dialogLogin.setCancelText("再去逛逛");
        dialogLogin.setOkText("去登录");
        dialogLogin.show();
    }

    private void showLoading() {
        if (sendingLoad == null) {
            sendingLoad = new DialogSendingComment(getContext());
        }
        sendingLoad.show();
    }

    private void hideLoading() {
        if (sendingLoad != null) {
            sendingLoad.dismiss();
        }
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (bottom - oldBottom > keyBordHeight) {
            if (sendCommentBDialog != null && sendCommentBDialog.isShowing() && sendCommentBDialog.isHide()) {
                sendCommentBDialog.dismiss();
            }
        }
    }
}
